package com.ldk.api.handler;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import org.codehaus.plexus.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;

import com.ldk.api.ApiVersion;
import com.ldk.api.ErrorCode;
import com.ldk.api.FileItem;
import com.ldk.api.ResponseObject;
import com.ldk.api.ResponseResult;
import com.ldk.base.framework.util.ConvertUtil;
import com.ldk.base.framework.util.RegexUtil;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.entity.AppVersion;
import com.ldk.framework.entity.Area;
import com.ldk.framework.entity.Dictdata;
import com.ldk.framework.entity.Feedback;
import com.ldk.framework.entity.RechargeDiscount;
import com.ldk.framework.entity.Region;
import com.ldk.framework.entity.ServiceConfig;
import com.ldk.framework.entity.StartPage;
import com.ldk.framework.service.IAppVersionService;
import com.ldk.framework.service.IAreaService;
import com.ldk.framework.service.IFeedbackService;
import com.ldk.framework.service.IRechargeDiscountService;
import com.ldk.framework.service.IRegionService;
import com.ldk.framework.service.IServiceConfigService;
import com.ldk.framework.service.IStartPageService;
import com.ldk.framework.unionpay.PayUtils;


/**
 * APP模块接口
 *
 * @author xiangwl
 * @date 2016-06-21
 * @time 11:16
 */
public class AppRequestHandler extends BaseRequestHandler {

    @Autowired
    private IStartPageService startPageService;
    @Autowired
    private IAppVersionService appVersionService;
    @Autowired
    private IServiceConfigService serviceConfigService;
    @Autowired
    private IRechargeDiscountService rechargeDiscountService;
    @Autowired
    private IFeedbackService feedbackService;
    @Autowired
    private IRegionService regionService;
    @Autowired
    private IAreaService areaService;

    /**
     * 获取启动页
     *
     * @param parms {platform}
     *              platform 平台
     * @return
     */
    @ApiVersion(value = {1})
    public ResponseObject getStartPage(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("app", "getStartPage");

        if (!checkRequireParms(parms, "platform")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String platform = String.valueOf(parms.get("platform"));

        StartPage query = new StartPage();
        query.setEnabled(true);
        query.setPlatform(platform);
        /*
        Calendar calendar = Calendar.getInstance();
        long curMonth = calendar.get(Calendar.MONTH) + 1;
        long curDay = calendar.get(Calendar.DAY_OF_MONTH);
        query.setStartMonth(curMonth);
        query.setStartDay(curDay);
        query.setEndMonth(curMonth);
        query.setEndDay(curDay);*/
        //按更新时间倒序查询
        Sort sort = new Sort(Direction.DESC, "update_time");
        StartPage startPage = startPageService.selectOne("", query, sort);
        if (startPage == null || StringUtils.isEmpty(startPage.getPicture())) {
            ResponseResult.exception(response, ErrorCode.APP_NOT_START_PAGE);
        } else {
            Map<String, Object> result = new Hashtable<String, Object>();
            if (!StringUtils.isEmpty(startPage.getPicture()) && !RegexUtil.isHttpUrl(startPage.getPicture())) {
                result.put("picture", getImgRoot() + startPage.getPicture());
            } else {
                result.put("picture", startPage.getPicture());
            }
            ResponseResult.success(response, result);
        }
        return response;
    }

    /**
     * 检测App版本是否需要更新
     *
     * @param parms {"platform","curVersion"}
     *              platform   平台值
     *              curVersion 当前版本号
     * @return ResponseObject
     */
    @ApiVersion(value = {1})
    public ResponseObject checkVersion(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("app", "checkVersion");
        if (!checkRequireParms(parms, "platform", "curVersion")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String platform = String.valueOf(parms.get("platform"));
        int curVersion = Integer.valueOf(parms.get("curVersion").toString());

        AppVersion query = new AppVersion();
        query.setEnabled(true);
        query.setPlatform(platform);
        query.setCurrentVersion(curVersion);

        AppVersion version = appVersionService.selectOne("", query);

        if (version == null || StringUtils.isEmpty(version.getDownUrl())) {
            ResponseResult.exception(response, ErrorCode.APP_NOT_NEW_VERSION);
        } else {
            Map<String, Object> result = new Hashtable<String, Object>();
            result.put("currentVersion", version.getCurrentVersion());
            result.put("versionNo", version.getVersionNo());
            result.put("versionInfo", version.getVersionInfo());
            result.put("size", version.getSize());
            result.put("downUrl", version.getDownUrl());
            result.put("forceUpdate", version.getForceUpdate());

            ResponseResult.success(response, result);
        }
        return response;
    }

    /**
     * 获取服务器当前时间戳
     *
     * @param parms {platform}
     *              platform 平台值
     * @return
     */
    @ApiVersion(value = {1})
    public ResponseObject getServerTime(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("app", "getServerTime");
        if (!checkRequireParms(parms, "platform")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        int platform = ConvertUtil.parseInt(parms.get("platform"));
        logger.info(platform + "");
        //服务器当前时间戳
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("serverTimespan", SystemUtil.getAllSeconds());
        ResponseResult.success(response, result);

        return response;
    }

    /**
     * 获取开通服务业务
     *
     * @param parms
     * @return
     */
    @ApiVersion(value = {1})
    public ResponseObject getOpenServices(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("app", "getOpenServices");

        if (!checkRequireParms(parms, "platform")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String platform = String.valueOf(parms.get("platform"));
        ServiceConfig query = new ServiceConfig();
        //query.setPlatform(platform);
        List<ServiceConfig> result = serviceConfigService.selectList("", query);

        if (result == null || result.isEmpty()) {
            response = ResponseResult.exception(response, ErrorCode.APP_OPEN_SERVICE_EMPTY);
        } else {
            response = ResponseResult.success(response, result);
        }

        return response;
    }

    /**
     * 获取充值折扣
     *
     * @param parms {platform}
     *              platform 平台值
     * @return
     */
    @ApiVersion(value = {1})
    public ResponseObject getRechargeDiscount(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("app", "getRechargeDiscount");
        if (!checkRequireParms(parms, "platform")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String platform = ConvertUtil.parseString(parms.get("platform"));
        logger.info(platform);
        RechargeDiscount query = new RechargeDiscount();
        query.setEnabled(true);

        List<RechargeDiscount> result = rechargeDiscountService.selectList("", query);
        if (result == null) {
            ResponseResult.exception(response, ErrorCode.APP_NOT_RECHARGE_DISCOUNT);
        } else {
            ResponseResult.success(response, result);
        }
        return response;
    }

    /**
     * 问题反馈
     *
     * @param parms openId
     *              content
     *              fileList
     * @return
     */
    @ApiVersion(value = {1})
    public ResponseObject feedback(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("app", "feedback");
        if (!checkRequireParms(parms, "openId", "content")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String content = ConvertUtil.parseString(parms.get("content"));
        List<FileItem> fileList = null;
        if (parms.get("fileList") != null) {
            try {
                @SuppressWarnings("unchecked")
                List<FileItem> list = (List<FileItem>) parms.get("fileList");
                fileList = list;
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }
        String image = "";
        if (fileList != null && !fileList.isEmpty()
                && !StringUtils.isBlank(fileList.get(0).getFileFullUrl())) {
            image = fileList.get(0).getFileFullUrl();
        }
        Boolean success = false;
        try {
            Feedback feedback = new Feedback();
            feedback.setOpenId(openId);
            feedback.setContent(content);
            feedback.setImage(image);
            feedback.setTime(SystemUtil.getAllSeconds());
            feedback.setStatus(1);//1提交2处理

            int row = feedbackService.insert("", feedback);
            success = row > 0;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        if (success) {
            ResponseResult.success(response, "反馈成功");
        } else {
            ResponseResult.exception(response, ErrorCode.APP_FEEDBACK_FAILED);
        }

        return response;
    }

    /**
     * 获取银行名称列表
     *
     * @param parms platform
     * @return
     */
    @ApiVersion(value = {1})
    public ResponseObject getBankNameList(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("app", "getBankNameList");
        if (!checkRequireParms(parms, "platform")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        List<Dictdata> list = getDictdataList(6);//6是银行名称的字典ID
        List<Map<String, String>> result = new ArrayList<Map<String, String>>();
        if (list != null && !list.isEmpty()) {
            for (Dictdata dictdata : list) {
                Map<String, String> item = new HashMap<String, String>();
                item.put("bankName", dictdata.getDataValue());
                result.add(item);
            }
        }
        ResponseResult.success(response, result);

        return response;
    }

    /**
     * 获取地区列表
     *
     * @param parms
     * @return
     */
    @ApiVersion(value = {1})
    public ResponseObject getRegionList(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("app", "getRegionList");
        if (!checkRequireParms(parms, "platform")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        Area query = new Area();
        query.setEnabled(true);
        List<Area> areaList = areaService.selectList("", query);
        List<Region> regionList = new ArrayList<>();
        for (Area area : areaList) {
            Region region = new Region();
            region.setRegionName(area.getAreaName());
            region.setRegionCode(area.getAreaCode());
            regionList.add(region);
        }
        /*List<Region> regionList = regionService.getChildRegionList("", 8);
        //ycs 191018 加上云南的
        List<Region> regionList_yunnan = regionService.getChildRegionList("", 30);
        for(int i=0;i<regionList_yunnan.size();i++) {
            regionList.add(regionList_yunnan.get(i));
        }*/

        ResponseResult.success(response, regionList);

        return response;
    }

    /**
     * 获取评价评语模板
     *
     * @param parms
     * @return
     * @paramplatform
     */
    @ApiVersion(value = {1})
    public ResponseObject getCommentList(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("app", "getCommentList");
        if (!checkRequireParms(parms, "dicid")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        int dicid = ConvertUtil.parseInt(parms.get("dicid"), 0);
        List<Dictdata> list = getDictdataList(dicid);
        ResponseResult.success(response, list);

        return response;
    }

}
